package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private SetmealDishMapper setmealDishMapper;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    /**
     * 新增菜功能
     * @param dishDto
     */
    @Override
    public void save(DishDto dishDto) {
        //补全代码
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        //默认状态为启售
        dishDto.setStatus(1);
        dishDto.setSort(0);
        dishMapper.save(dishDto);

        //拿到口味集合
        List<DishFlavor> flavorList = dishDto.getFlavors();
        if (flavorList.size()==0){
            return;
        }
        //stream流把数据写入口味集合
        List<DishFlavor> dishFlavorList = flavorList.stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            return dishFlavor;
        }).collect(Collectors.toList());

        dishFlavorMapper.batchSave(dishFlavorList);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 分页查询功能
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        //根据名字模糊查询含有name的菜
        List<Dish> dishList = dishMapper.findByName(name);
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);
        //stream流传入数据
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryMapper.findById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        Page<DishDto> dishDtoPage = new Page<>(dishDtoList, pageInfo.getTotal());
        return R.success(dishDtoPage);
    }

    /**
     * 根据ID查找菜品
     * @param dishId
     * @return
     */
    @Override
    public R<DishDto> findById(Long dishId) {
        Dish dish = dishMapper.findById(dishId);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(dishId);

        dishDto.setFlavors(dishFlavorList);

        return R.success(dishDto);
    }

    /**
     * 修改菜功能
     * @param dishDto
     */
    @Override
    public void update(DishDto dishDto) {
        dishDto.setUpdateTime(LocalDateTime.now());

        dishMapper.updateById(dishDto);

        dishFlavorMapper.deleteByDishId(dishDto.getId());

        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors.size()==0){
            return;
        }
        //stream流传入数据,也可以使用增强for循环代替
        List<DishFlavor> collect = flavors.stream().map(flavor -> {
            flavor.setDishId(dishDto.getId());
            flavor.setCreateTime(LocalDateTime.now());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateUser(dishDto.getCreateUser());
            flavor.setUpdateUser(dishDto.getUpdateUser());
            return flavor;
        }).collect(Collectors.toList());

        dishFlavorMapper.batchSave(collect);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 移动端显示菜品
     * @param categoryId
     * @param status
     * @return
     */
    @Override
    public List<DishDto> findByCategoryId(Long categoryId,Integer status) {

        String key = "dish_"+categoryId+"_"+status;

        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList == null){

            List<DishDto> dishList = dishMapper.findByCategoryId(categoryId,status);
                dishDtoList = dishList.stream().map(dish -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(dish.getId());
                dishDto.setFlavors(dishFlavorList);
                return dishDto;
            }).collect(Collectors.toList());

            redisTemplate.opsForValue().set(key,dishDtoList);
        }


        return dishDtoList;
    }

    /**
     * 停售启售功能
     * @param status
     * @param ids
     */
    @Override
    public void updateStatus(Integer status, List<Long> ids) {
        dishMapper.updateStatus(status,ids);
    }


    /**
     * 根据id删除菜品
     * @param ids
     */
    @Override
    public void deleteByIds(List<Long> ids) {
        //查找状态
        int count = dishMapper.findStatusCount(ids);

        int count1 = setmealDishMapper.findCount(ids);

        if (count>0){
            throw new CustomerException("这些菜还在售卖,无法删除");
        }

        if (count1>0){
            throw new CustomerException("此菜品在套餐中售卖,不能删除");
        }


        dishMapper.deleteByIds(ids);

        dishFlavorMapper.deleteByDishIds(ids);
    }
}
